import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import { themeUtils, THEME_CONFIG } from '../../utils/themeConfig';
import type { ThemeMode, ThemeState } from '../../types/theme';

// 从配置工具获取初始主题
const getInitialTheme = (): ThemeMode => {
  return themeUtils.getStoredTheme();
};

const initialState: ThemeState = {
  mode: getInitialTheme(),
};

const themeSlice = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    toggleTheme: (state) => {
      state.mode = state.mode === 'light' ? 'dark' : 'light';
      // 使用配置工具保存和应用主题
      themeUtils.saveTheme(state.mode);
      themeUtils.applyTheme(state.mode);
    },
    setTheme: (state, action: PayloadAction<ThemeMode>) => {
      state.mode = action.payload;
      // 使用配置工具保存和应用主题
      themeUtils.saveTheme(state.mode);
      themeUtils.applyTheme(state.mode);
    },
    // 新增：根据系统主题设置
    setSystemTheme: (state) => {
      const systemTheme = themeUtils.getSystemTheme();
      state.mode = systemTheme;
      themeUtils.saveTheme(state.mode);
      themeUtils.applyTheme(state.mode);
    },
  },
});

export const { toggleTheme, setTheme, setSystemTheme } = themeSlice.actions;
export default themeSlice.reducer;
